package com.book.backend.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aliyun.broadscope.bailian.sdk.consts.HttpHeaderConsts;
import com.book.backend.common.R;
import com.book.backend.config.GiteeConstant;
import com.book.backend.pojo.SocialUser;
import com.book.backend.pojo.Users;
import com.book.backend.service.AiService;
import com.book.backend.service.UsersService;
import com.book.backend.utils.HttpUtils;
import com.book.backend.utils.JwtKit;
import com.book.backend.utils.VeificationgCode;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description: 处理社交登录请求
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-06-28 10:16
 **/

@Slf4j
@Controller
public class OAuth2Controller {
    @Resource
    private JwtKit jwtKit;

    @Autowired
    private UsersService usersService;

    @Resource
    private AiService aiService;
/*    @GetMapping(value = "/stream", produces = HttpHeaderConsts.MediaType.TEXT_EVENT_STREAM_VALUE)
    @ApiOperation("ai流式输出")
    @ResponseBody
    public SseEmitter streamOutput(@RequestParam String msg) throws IOException {
        System.out.println(msg+"*()*");
        return aiService.outPut(msg);
    }*/

    /**
     * 借阅用户注册
     *
     * @param users 借阅者用户
     * @return 返回R通用数据
     */

    @PostMapping("/user/register")
    @ApiOperation("用户注册")
    @ResponseBody
    public R register(@RequestBody Users users) {
        return usersService.register(users);
    }

    @GetMapping("/verifyCode")
    @ResponseBody
    public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
        VeificationgCode code = new VeificationgCode();
        BufferedImage image = code.getImage();
        String text = code.getText();
        System.out.println(text+"   **********");
        session.setAttribute("verify_code",text);
        VeificationgCode.output(image,response.getOutputStream());
    }


    @GetMapping(value = "/oauth2.0/weibo/success")
    public void weibo(@RequestParam(value = "error" , required=false) String error,@RequestParam(value = "code" , required=false) String code,HttpServletResponse resp, HttpSession session) throws Exception {
        if (error != null){
            resp.sendRedirect("http://localhost:8081/#/login");
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("grant_type","authorization_code");
        params.put("code",code);
        params.put("client_id", GiteeConstant.clientId);
        params.put("redirect_uri",GiteeConstant.callback);
        params.put("client_secret",GiteeConstant.secret);


        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), params, new HashMap<>());
        System.out.println(response.getStatusLine().getStatusCode()+ "*&*&*" );
        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了access_token,转为通用社交登录对象
            String json = EntityUtils.toString(response.getEntity());
            //String json = JSON.toJSONString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //知道了哪个社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            System.out.println("登录后用code换取的token值：" + socialUser.getAccessToken());
            //调用远程服务
            R oauthLogin = usersService.oauthLogin(socialUser);
            if (oauthLogin.getStatus() == 200) {
                Users data = (Users) oauthLogin.getData();
                log.info("登录成功：用户信息：{}",data.toString());

                //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
                //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                session.setAttribute("loginUser",data);
                System.out.println(session.getAttribute("loginUser"));
                //2、登录成功跳回首页
                resp.sendRedirect("http://localhost:8081/#/index");

//                return "redirect:http://localhost:8081/#/index";
            } else {

                resp.sendRedirect("http://localhost:8081/#/login");
//                return "redirect:http://localhost:8081/#/login";
            }

        } else {
            resp.sendRedirect("http://localhost:8081/login");
//            return "redirect:http://localhost:8081/#/login";
        }

    }
    @GetMapping("/getsession")
    @ResponseBody
    public R login(HttpSession session) {
        System.out.println(session.getAttribute("loginUser"));
        Users attribute = (Users) session.getAttribute("loginUser");
        String token = jwtKit.generateToken(attribute);
        R<Users> result = new R<>();
        result.setStatus(200);
        result.add("token", token);
        result.setMsg("登录成功");
        result.add("id", attribute.getUserId());
        return result;
    }

}
